import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import router from '@/router'

// 创建axios实例
const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    
    // 添加认证token
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`
    }
    
    // 添加请求ID用于追踪
    config.headers['X-Request-ID'] = generateRequestId()
    
    // 添加时间戳防止缓存
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        _t: Date.now()
      }
    }
    
    return config
  },
  (error) => {
    console.error('请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    const { data } = response
    
    // 统一处理响应格式
    if (data.code !== undefined) {
      if (data.code === 200 || data.code === 0) {
        return data
      } else {
        // 业务错误
        const message = data.message || '请求失败'
        ElMessage.error(message)
        return Promise.reject(new Error(message))
      }
    }
    
    // 直接返回数据
    return data
  },
  async (error) => {
    const { response, config } = error
    const userStore = useUserStore()
    
    // 网络错误
    if (!response) {
      ElMessage.error('网络连接失败，请检查网络设置')
      return Promise.reject(error)
    }
    
    const { status, data } = response
    
    switch (status) {
      case 401:
        // 未授权，清除token并跳转到登录页
        ElMessage.error('登录已过期，请重新登录')
        await userStore.logout()
        router.push('/auth/login')
        break
        
      case 403:
        ElMessage.error('没有权限访问该资源')
        break
        
      case 404:
        ElMessage.error('请求的资源不存在')
        break
        
      case 422:
        // 表单验证错误
        if (data.errors) {
          const firstError = Object.values(data.errors)[0]
          ElMessage.error(Array.isArray(firstError) ? firstError[0] : firstError)
        } else {
          ElMessage.error(data.message || '请求参数错误')
        }
        break
        
      case 429:
        ElMessage.error('请求过于频繁，请稍后再试')
        break
        
      case 500:
        ElMessage.error('服务器内部错误，请稍后再试')
        break
        
      case 502:
      case 503:
      case 504:
        ElMessage.error('服务暂时不可用，请稍后再试')
        break
        
      default:
        ElMessage.error(data?.message || `请求失败 (${status})`)
    }
    
    return Promise.reject(error)
  }
)

// 生成请求ID
function generateRequestId() {
  return Math.random().toString(36).substring(2) + Date.now().toString(36)
}

// 文件上传
export const uploadFile = (file, onProgress) => {
  const formData = new FormData()
  formData.append('file', file)
  
  return request.post('/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress: (progressEvent) => {
      if (onProgress) {
        const percentCompleted = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        )
        onProgress(percentCompleted)
      }
    }
  })
}

// 批量上传文件
export const uploadFiles = (files, onProgress) => {
  const formData = new FormData()
  files.forEach((file, index) => {
    formData.append(`files[${index}]`, file)
  })
  
  return request.post('/upload/batch', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress: (progressEvent) => {
      if (onProgress) {
        const percentCompleted = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        )
        onProgress(percentCompleted)
      }
    }
  })
}

// 下载文件
export const downloadFile = (url, filename) => {
  return request.get(url, {
    responseType: 'blob'
  }).then(response => {
    const blob = new Blob([response.data])
    const downloadUrl = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = downloadUrl
    link.download = filename || 'download'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(downloadUrl)
  })
}

// 请求重试
export const retryRequest = (requestFn, maxRetries = 3, delay = 1000) => {
  return new Promise((resolve, reject) => {
    let retries = 0
    
    const attempt = () => {
      requestFn()
        .then(resolve)
        .catch((error) => {
          retries++
          if (retries < maxRetries) {
            setTimeout(attempt, delay * retries)
          } else {
            reject(error)
          }
        })
    }
    
    attempt()
  })
}

// 并发请求控制
export const concurrentRequest = (requests, limit = 5) => {
  return new Promise((resolve, reject) => {
    const results = []
    let completed = 0
    let index = 0
    
    const execute = () => {
      if (index >= requests.length) {
        if (completed === requests.length) {
          resolve(results)
        }
        return
      }
      
      const currentIndex = index++
      const request = requests[currentIndex]
      
      request()
        .then((result) => {
          results[currentIndex] = { success: true, data: result }
        })
        .catch((error) => {
          results[currentIndex] = { success: false, error }
        })
        .finally(() => {
          completed++
          if (completed === requests.length) {
            resolve(results)
          } else {
            execute()
          }
        })
    }
    
    // 启动并发请求
    for (let i = 0; i < Math.min(limit, requests.length); i++) {
      execute()
    }
  })
}

// 请求缓存
const requestCache = new Map()

export const cachedRequest = (key, requestFn, ttl = 5 * 60 * 1000) => {
  const cached = requestCache.get(key)
  
  if (cached && Date.now() - cached.timestamp < ttl) {
    return Promise.resolve(cached.data)
  }
  
  return requestFn().then((data) => {
    requestCache.set(key, {
      data,
      timestamp: Date.now()
    })
    return data
  })
}

// 清除缓存
export const clearCache = (key) => {
  if (key) {
    requestCache.delete(key)
  } else {
    requestCache.clear()
  }
}

export default request